package com.yncmcc.Log;

import com.yncmcc.Entity.*;
import com.yncmcc.Service.Interface.AdminService;
import com.yncmcc.Service.Interface.ContractsService;
import com.yncmcc.Service.Interface.LogsService;
import com.yncmcc.Service.Interface.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

import static com.yncmcc.Entity.ContractsEntity_.contractId;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Aspect
@Component
public class UserLog {
    private static String Domain = "普通用户";
    private static Short AdminRight = 0;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ContractsService contractsService;
    @Autowired
    private LogsService Log;

//    @Before("execution(* com.yncmcc.Controller.UserControllerImpl.login(..))")
//    public void checkUserRight(JoinPoint joinPoint){
//        Object[] values = joinPoint.getArgs();
//        String userName = (String) values[0];
//
//    }
    @Before("execution(* com.yncmcc.Controller.UserControllerImpl.login(..))")
    public void userLoginLog(JoinPoint joinPoint){
        Object[] values = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) values[values.length - 2];
        LogsEntity logsEntity = new LogsEntity();

        String userName = (String) values[0];
        UserEntity userEntity = userService.findByUserName(userName);

        AdminEntity adminEntity = adminService.findByAdminName(userName);
        if(userEntity==null && adminEntity!=null){
            Log.saveLog(adminEntity.getAdminId(),request.getRemoteAddr(),AdminRight,"登录");
        }else if(userEntity!=null && adminEntity == null){
            Log.saveLog(userEntity.getUserId(),request.getRemoteAddr(),userEntity.getUserRight(),"登录");
        }
    }

    @Before("execution(* com.yncmcc.Controller.UserControllerImpl.logout(..))")
    public void userLogoutLog(JoinPoint joinPoint){
        Object[] value = joinPoint.getArgs();
        HttpSession session = (HttpSession) value[value.length - 1];
        HttpServletRequest request = (HttpServletRequest) value[value.length - 2];
        String userId = (String) session.getAttribute("userId");
        if (userId != null) {
            UserEntity userEntity = userService.findByUserId(userId);
            Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), "登出");
        }else{
            String adminId = (String) session.getAttribute("adminId");
            if (adminId != null) {
                AdminEntity adminEntity = adminService.findAdminById(adminId);
                Log.saveLog(adminEntity.getAdminId(), request.getRemoteAddr(), AdminRight, "登出");
            }
        }
    }

    @Before("execution(* com.yncmcc.Controller.UserControllerImpl.getSelfInfo(..))")
    public void userGetInfoLog(JoinPoint joinPoint){
        Object[] value = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) value[value.length - 2];
        HttpSession session = (HttpSession) value[value.length - 1];
        String userId = (String) session.getAttribute("userId");
        if (userId != null) {
            UserEntity userEntity = userService.findByUserId(userId);
            Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), "用户查询个人信息");
        }
    }

    @Before("execution(* com.yncmcc.Controller.UserControllerImpl.updatePass(..))")
    public void userUpdatePassLog(JoinPoint joinPoint){
        Object[] value = joinPoint.getArgs();
        HttpSession session = (HttpSession) value[value.length - 1];
        HttpServletRequest request = (HttpServletRequest) value[value.length - 2];
        String userId = (String) session.getAttribute("userId");
        if (userId != null) {
            UserEntity userEntity = userService.findByUserId(userId);
            Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), "用户更改密码");
        }
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.addContract(..))")
    public Object userAddConLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "添加");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.updateContract(..))")
    public Object userUpdateConLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "更新");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.findContract(..))")
    public Object userFindConLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "查找集");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.addContractByExcel(..))")
    public Object userAddConByExcelLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "excel");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.addPeriod(..))")
    public Object userAddPerLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "添加分期");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.getContractByID(..))")
    public Object userGetContractByIDLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "查找");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.getPeriodByCID(..))")
    public Object userGetPeriodByIDLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "查找合同分期");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.updatePeriod(..))")
    public Object userUpdatePeriodLog(ProceedingJoinPoint joinPoint) throws Throwable {
        return setContractOpLog(joinPoint, "更新合同分期");
    }

    @Around("execution(* com.yncmcc.Controller.UserControllerImpl.updateEmail(..))")
    public Object userUpdateEmailLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] value = joinPoint.getArgs();
        HttpSession session = (HttpSession) value[value.length - 1];
        HttpServletRequest request = (HttpServletRequest) value[value.length - 2];
//        String type = request.getParameter("type");
        String userId = (String) session.getAttribute("userId");
        UserEntity userEntity = userService.findByUserId(userId);
        String des = "用户更新" + (String)value[value.length - 4] + "邮箱，用户编号：" + userEntity.getUserName();
        Map<String, Object> response = (Map<String, Object>) joinPoint.proceed();
        if (userId != null) {
            if (response.get("status").equals("ok")){
                Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), des);
            }else{
//                Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), "用户" + op + "合同失败，失败原因：" + response.get("des"));
            }
        }
        return response;
    }


    public Object setContractOpLog(ProceedingJoinPoint joinPoint, String op) throws Throwable {
        Object[] value = joinPoint.getArgs();
        HttpSession session = (HttpSession) value[value.length - 1];
        HttpServletRequest request = (HttpServletRequest) value[value.length - 2];
        String userId = (String) session.getAttribute("userId");
        String des = "";

        if(op.equals("查找")){
            String contractId = (String) value[0];
            ContractsEntity contractsEntity = contractsService.findByContractID(contractId);
            des = "用户" + op + "合同操作，合同编号：" + contractsEntity.getContractSerial();
        }else if(op.equals("查找集")){
            des = "用户查找合同集操作";
        }else if(op.equals("excel")){
            des = "用户通过excel文件添加合同";
        }else if(op.equals("添加分期")){
            PeriodEntity periodEntity = (PeriodEntity) value[0];
            des = "用户添加合同分期，合同编号：" + periodEntity.getContractId();
        }else if(op.equals("查找合同分期")){
            String contractId = (String) value[0];
            des = "用户查找合同分期，合同编号：" + contractId;
        }else if(op.equals("更新合同分期")){
            PeriodEntity periodEntity = (PeriodEntity) value[0];
            des = "用户更新合同分期，合同编号：" + periodEntity.getContractId();
        }else{
            ContractsEntity contractsEntity = (ContractsEntity) value[0];
            des = "用户" + op + "合同操作，合同编号：" + contractsEntity.getContractSerial();
        }
        Map<String, Object> response = (Map<String, Object>) joinPoint.proceed();
        if (userId != null) {
            UserEntity userEntity = userService.findByUserId(userId);
            if (response.get("status").equals("ok")){
                Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), des);
            }else{
                Log.saveLog(userEntity.getUserId(), request.getRemoteAddr(), userEntity.getUserRight(), "用户" + op + "合同失败，失败原因：" + response.get("des"));
            }
        }
        return response;
    }
}

